/**   
 * @Title: ServerFragment.java 
 * @Package: com.rename.icode.activity 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-2-11 下午2:45:30 
 * @version  
 */

package com.rename.icode.activity;

import android.R.integer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.rename.icode.R;
import com.rename.icode.comm.Constants;
import com.rename.icode.manager.UserManager;
import com.rename.icode.model.CodeFile;
import com.rename.icode.utils.FileUtil;
import com.rename.icode.utils.LogUtil;
import com.rename.icode.view.CodeFilesAdapter;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 实现了...功能
 * @author Administrator
 * @date 2015-2-11 下午2:45:30
 * @version V1.0
 */

public class ServerFragment extends Fragment {

	private static final String TAG = "ServerFragment";
	private View mServerFragmentView;
	private static ServerFragment mServerFragment;
	private Context mContext;

	private ListView mFileList;
	private OnClickListener mFileOnClickListener;
	private CodeFilesAdapter mAdapter;
	private List<CodeFile> mCodeFiles = new ArrayList<CodeFile>();
	private ServerReceiver mReceiver = null;

	private CodeFile mCodeFile;
	private final static int SHOW_CODE_VIEW = 0;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_CODE_VIEW:
				LogUtil.i("gg", "mCodeFile.getPath() is " + mCodeFile.getPath());
				if (FileUtil.isFileExist(mCodeFile.getPath())) {
					LogUtil.i("gg", "download file success");
					((MainActivity) mContext).changeLayout(MainActivity.CODE); // 切换到代码编辑界面
					((MainActivity) mContext).showCodeViewByLanguage(true,
							mCodeFile); // 打开指定代码
					((MainActivity) mContext).fromServer = true; //
				} else {
					Toast.makeText(mContext, "文件不存在", 0).show();
				}
				break;

			default:
				break;
			}
		}

	};

	public ServerFragment() {
		super();
	}

	public static ServerFragment getServerFragmentIntance() {
		if (mServerFragment != null) {
			return mServerFragment;
		} else {
			mServerFragment = new ServerFragment();
			return mServerFragment;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mServerFragmentView = inflater.inflate(R.layout.server_info, container,
				false);

		init();

		return mServerFragmentView;
	}

	private void init() {
		LogUtil.i(TAG, "ServerFragment init...");
		mContext = getActivity();

		mFileOnClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				CodeFile codeFile = (CodeFile) v.findViewById(
						R.id.file_name_txt).getTag();
				LogUtil.i("gg", "文件名：" + codeFile.getName());
				mCodeFile = codeFile;

				new Thread() {

					@Override
					public void run() {
						// TODO 从服务器下载文件，并存放到"/code/server/"目录下
						String urlString = Constants.DOWNLOAD_URL
								+ UserManager.getInstance().getUser().getId()
								+ "/" + mCodeFile.getName();
						String filePath = Constants.CODE_SERVER_DIR
								+ mCodeFile.getName();
						downloadFile(urlString, filePath);

						mHandler.sendEmptyMessage(SHOW_CODE_VIEW);
					}

				}.start();

			}
		};
		mAdapter = new CodeFilesAdapter(mContext, mCodeFiles,
				CodeFilesAdapter.SHOW_MODE);
		mAdapter.setOnClickListener(mFileOnClickListener);
		mFileList = (ListView) mServerFragmentView
				.findViewById(R.id.server_list);
		mFileList.setAdapter(mAdapter);
	}

	private void initReceiver() {
		if (null == mReceiver) {
			mReceiver = new ServerReceiver();
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction(Constants.SERVER_REFRESH);
			intentFilter.addAction(Constants.PAGE_LOAD_FINISHED);
			mContext.registerReceiver(mReceiver, intentFilter);
		}
	}

	private class ServerReceiver extends BroadcastReceiver {

		/**
		 * Description
		 * 
		 * @param context
		 * @param intent
		 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
		 *      android.content.Intent)
		 */

		@Override
		public void onReceive(Context context, Intent intent) {
			LogUtil.i(TAG, "接受到了广播: " + intent.getAction());
			String action = intent.getAction();

			if (Constants.SERVER_REFRESH.equals(action)) {
				LogUtil.i(TAG, "SERVER_REFRESH...");
				refreshCodeFileListView();
			} else if (Constants.PAGE_LOAD_FINISHED.equals(action)) {
				LogUtil.i(TAG, "PAGE_LOAD_FINISHED...");

			}
		}

	}

	private void refreshCodeFileListView() {
		mCodeFiles = UserManager.getInstance().getUser().getServerData();
		// 注释
		// for(CodeFile codeFile : mCodeFiles){
		// LogUtil.i("aa", "serverfragment文件刷新 codefile is " +
		// codeFile.getName());
		// }
		LogUtil.i("gg", "mCodeFiles is null is " + (null == mCodeFiles));
		mAdapter.refreshList(mCodeFiles);
	}

	/**
	 * 
	 * @Description 从服务器下载指定文件
	 * @author Administrator
	 * @param urlString
	 *            服务器资源路径
	 * @param filePath
	 *            下载到本地的存放路径
	 */
	private void downloadFile(String urlString, String filePath) {
		LogUtil.i("gg", "url is " + urlString);
		LogUtil.i("gg", "filepath is " + filePath);
		File file = null;
		try {
			URL url = new URL(urlString);
			InputStream in = url.openStream();
			file = new File(filePath);
			OutputStream out = new BufferedOutputStream(new FileOutputStream(
					file));

			for (int b; (b = in.read()) != -1;) {
				LogUtil.i("gg", "b is " + b);
				out.write(b);
			}
			out.close();
			in.close();
		} catch (Exception e) {
			Log.i(TAG, "downloadFile err " + e.toString());
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		initReceiver();
		refreshCodeFileListView();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mContext.unregisterReceiver(mReceiver);
		mReceiver = null;
	}
}
